package user

import (
	"bbs-web/internal/domain"
	"bbs-web/internal/repository/dao"
	"context"
	"errors"
	"golang.org/x/crypto/bcrypt"
)

type IuserRepo interface {
	RegUser(ctx context.Context, u domain.UserInfo) error
	LoginCheck(ctx context.Context, u domain.UserInfo) (*dao.UserMode, error)
	CreateUser(ctx context.Context, u domain.UserInfo) (*dao.UserMode, error)
	//SearchUserList(ctx context.Context, u domain.UserInfo) (*dao.UserMode, error)
}

type userRepo struct {
	da dao.IuserDao
}

func NewUserRepo(dao dao.IuserDao) IuserRepo {
	return &userRepo{da: dao}
}

func (r *userRepo) RegUser(ctx context.Context, u domain.UserInfo) error {
	////检查用户名是否存在
	//exist, err := r.dao.FindByUserName(ctx, u.UserName)
	//if err != nil {
	//	return err
	//}
	//if exist {
	//	return errors.New("用户已经存在")
	//}

	return r.da.Insert(ctx, dao.UserMode{
		Username: u.UserName,
		Password: u.Password,
		Nickname: u.NickName,
		IsAdmin:  0,
	})
}

func (r *userRepo) LoginCheck(ctx context.Context, u domain.UserInfo) (*dao.UserMode, error) {
	//检查用户名是否存在
	data, err := r.da.FindByUserName(ctx, u.UserName)
	if err != nil {
		return nil, err
	}
	//检查登录密码是否正确
	err = bcrypt.CompareHashAndPassword([]byte(data.Password), []byte(u.Password))
	if err != nil {
		return nil, errors.New("密码不对")
	}
	return &data, nil
}

func (r *userRepo) CreateUser(ctx context.Context, u domain.UserInfo) (*dao.UserMode, error) {
	data, err := r.da.FindByPhone(ctx, u.UserName)
	if len(data.Phone) != 0 {
		return nil, errors.New("手机号码已存在无法创建用户")
	}
	encryptpwd, err := bcrypt.GenerateFromPassword([]byte(u.Password), bcrypt.DefaultCost)
	if err != nil {
		return nil, errors.New("密码加密失败")
	}
	u.Password = string(encryptpwd)
	err = r.da.Insert(ctx, dao.UserMode{
		Username:  u.UserName,
		Phone:     u.Phone,
		Password:  u.Password,
		Nickname:  u.NickName,
		Active:    true,
		IsAdmin:   u.IsAdmin,
		CreatorId: u.ID,
	})
	return &data, nil

}

//func (r *userRepo) SearchUserList(ctx context.Context, search vo.UserSearchReq) ([]dao.UserMode, error) {
//	var userList []dao.UserMode
//	var db *gorm.DB
//	if len(strings.TrimSpace(search.SearchKey)) != 0 {
//		db = db.WithContext(ctx).Where("username like ? or phone like ?", "%"+search.SearchKey+"%", "%"+search.SearchKey+"%")
//	}
//	if len(strings.TrimSpace(search.SearchKey)) != 0 {
//		db = db.WithContext(ctx).Where("create_at >= ?", search.CreateDate)
//	}
//	if len(strings.TrimSpace(search.SearchKey)) != 0 {
//
//	}
//}
